package com.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.entry.dto.group.GroupChatMessageDTO;
import com.chat.entry.enums.ReadStatus;
import com.chat.entry.po.GroupMember;
import com.chat.entry.po.GroupMessage;
import com.chat.entry.po.GroupMessageUnread;
import com.chat.mapper.GroupMemberMapper;
import com.chat.mapper.GroupMessageMapper;
import com.chat.mapper.GroupMessageUnreadMapper;
import com.chat.result.Result;
import com.chat.service.IGroupMessageService;
import com.chat.service.IGroupMessageUnreadService;
import com.chat.websocket.GroupChatMessageHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 群聊消息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-09-05
 */
@Service
@RequiredArgsConstructor
public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, GroupMessage> implements IGroupMessageService {
    private final GroupMemberMapper groupMemberMapper;
    private final GroupMessageUnreadMapper groupMessageUnreadMapper;
    private final GroupChatMessageHandler groupChatMessageHandler;

    @Transactional
    @Override
    public Result sendMessage(GroupChatMessageDTO sendGroupMessageDTO) {
        // 保存群消息
        GroupMessage groupMessage = new GroupMessage();
        groupMessage.setGroupId(sendGroupMessageDTO.getGroupId());
        groupMessage.setSenderId(sendGroupMessageDTO.getSenderId());
        groupMessage.setContent(sendGroupMessageDTO.getContent());
        groupMessage.setType(sendGroupMessageDTO.getType());
        baseMapper.insert(groupMessage);

        // 查询该群成员
        List<Integer> memberIds = groupMemberMapper.selectList(
                        new LambdaQueryWrapper<GroupMember>()
                                .eq(GroupMember::getGroupId, sendGroupMessageDTO.getGroupId())
                ).stream()
                .map(GroupMember::getUserId)
                .collect(Collectors.toList());

        // 为每位群员插入一条未读消息（自己除外）
        List<GroupMessageUnread> groupMessageUnreads = new ArrayList<>();
        memberIds.forEach(memberId -> {
            if (!memberId.equals(sendGroupMessageDTO.getSenderId())) {
                GroupMessageUnread groupMessageUnread = new GroupMessageUnread();
                groupMessageUnread.setMessageId(groupMessage.getId());
                groupMessageUnread.setReceiver(memberId);
                groupMessageUnread.setReadStatus(ReadStatus.UNREAD);
                groupMessageUnreads.add(groupMessageUnread);
            }
        });

        if (!groupMessageUnreads.isEmpty()) {
            groupMessageUnreadMapper.insertBatch(groupMessageUnreads);
        }

        // 推送消息
        groupChatMessageHandler.sendMessage(memberIds, groupMessage);

        return Result.success("消息发送成功", null);
    }
}
